package jp.co.kayo.gae.takidashibot.service;

import java.io.IOException;
import java.util.logging.Logger;

import jp.co.kayo.gae.takidashibot.utils.TwitterClient;
import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.OAuthAuthorization;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;

public class TwitterSerivce {
    public static final Logger log = Logger.getLogger(TwitterSerivce.class.getName());
    
    private AccessToken loadAccessToken(int n) {
        if(n!=-1){
            String token = System.getProperty("oauth.token"+n);
            String tokensecret = System.getProperty("oauth.tokensecret"+n);
            return new AccessToken(token, tokensecret);
        }
        else{
            String token = System.getProperty("oauth.token");
            String tokensecret = System.getProperty("oauth.tokensecret");
            return new AccessToken(token, tokensecret);
        }
    }
    
    public String getScreenName(int n){
        if(n!=-1){
            return System.getProperty("screen_name"+n);
        }
        else{
            return System.getProperty("screen_name");
        }
    }

    public TwitterClient getTwitter(int n) throws IOException {
        // まず自分のフォロワーをチェックする
        AccessToken accessToken = loadAccessToken(n);
        Configuration config = new ConfigurationBuilder().build();
        Twitter twitter = new TwitterFactory(config)
                .getInstance(new OAuthAuthorization(config));
        twitter.setOAuthAccessToken(accessToken);
        
        TwitterClient client = new TwitterClient(twitter, getScreenName(n));
        return client;
    }
}
